package vip.xiaonuo.issued.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.core.file.FileOperator;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.devicehistory.entity.DeviceHistory;
import vip.xiaonuo.facedoor.modular.devicehistory.service.DeviceHistoryService;
import vip.xiaonuo.facedoor.modular.deviceset.entity.DwDeviceSet;
import vip.xiaonuo.facedoor.modular.deviceset.service.DwDeviceSetService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.modular.visitor.constant.VisitorConstant;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.facedoor.modular.visitorhistory.entity.VisitorHistory;
import vip.xiaonuo.facedoor.modular.visitorhistory.service.VisitorHistoryService;
import vip.xiaonuo.facedoor.vo.haiqing.HeartBeat;
import vip.xiaonuo.issued.controller.vo.CardVo;
import vip.xiaonuo.issued.controller.vo.VerifyWithSnapVo;
import vip.xiaonuo.sys.modular.file.enums.FileTypeEnum;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class HqCallBackController {


    @Resource
    private DwDeviceSetService dwDeviceSetService;

    @Resource
    private DeviceBaseService deviceBaseService;


    @Resource
    private MemberUserService memberUserService;

    @Resource
    private DeviceHistoryService deviceHistoryService;

    @Resource
    private VisitorService visitorService;

    @Resource
    private SysFileInfoService fileInfoService;

    @Resource
    private SysOrgService sysOrgService;

    @Resource
    private VisitorHistoryService visitorHistoryService;

    @PostMapping("/subscribe/heartbeat")
    public HeartBeat.Response heartBeat(@RequestBody HeartBeat heartBeat) {
        log.info("收到设备心跳【{}】", JSON.toJSONString(heartBeat));
        HeartBeat.Response response = new HeartBeat.Response();
        DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceId, heartBeat.getInfo().getDeviceID()));
        if (deviceSet != null) {
            DeviceBase deviceBase = deviceBaseService.getById(deviceSet.getDeviceBaseId());
            if (deviceBase == null) {
                log.error("设备不存在【{}】", JSON.toJSONString(heartBeat));
                response.setCode("200");
                response.setDesc("OK");
                return response;
            }
            log.info("收到设备【{}】心跳", deviceBase.getName());
            deviceBase.setDeviceState("1");
            deviceBase.setLastOnlineTime(new Date());
            deviceBaseService.updateById(deviceBase);
            response.setDesc("OK");
            response.setCode("200");
        } else {
            log.error("设备未设置【{}】", JSON.toJSONString(heartBeat));
            response.setCode("200");
            response.setDesc("OK");
        }
        return response;
    }


    public static void main(String[] args) {
        String md5 = DigestUtils.md5Hex("{\"heartbeat\":30}");
        System.out.println(md5);
    }

    @PostMapping("/subscribe/VerifyWithSnap")
    public HeartBeat.Response heartBeat(@RequestBody String body) {
        HeartBeat.Response response = new HeartBeat.Response();
        try {
            VerifyWithSnapVo verifyWithSnapVo = JSON.parseObject(body, VerifyWithSnapVo.class);
            log.info("收到通行记录【{}】", body);
            VerifyWithSnapVo.InfoDTO info = verifyWithSnapVo.getInfo();
            DateTime cpmparedDate = DateUtil.parse(verifyWithSnapVo.getInfo().getCreateTime().replace("T", " "), "yyyy-MM-dd HH:mm:ss");

            DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceId, verifyWithSnapVo.getInfo().getDeviceID()));
            if (deviceSet != null) {
                DeviceBase deviceBase = deviceBaseService.getById(deviceSet.getDeviceBaseId());
                if (deviceBase == null) {
                    log.error("设备不存在【{}】", JSON.toJSONString(verifyWithSnapVo));
                    response.setCode("200");
                    response.setDesc("OK");
                    return response;
                }
                if (ObjectUtil.equal(info.getTempvalid(), 0)) {
                    log.info("设备收到【{}】内部人员通行记录", deviceBase.getName());
                    MemberUser member = memberUserService.getById(info.getCustomizeID().toString().substring(1));
                    DeviceHistory deviceHistory = new DeviceHistory();
                    deviceHistory.setMemberName(info.getName());
                    deviceHistory.setMemberId((long) info.getCustomizeID());
                    deviceHistory.setDeviceBaseId(deviceBase.getId());
                    deviceHistory.setDeviceName(deviceBase.getName());
                    deviceHistory.setIcNum(verifyWithSnapVo.getInfo().getRFIDCard());
                    if (member != null) {
                        deviceHistory.setMemberJobNum(member.getJobNum());
                        deviceHistory.setOrgId(member.getOrgId());
                    }
                    deviceHistory.setDeviceCurrentDate(cpmparedDate);
                    deviceHistory.setIcNum(info.getRFIDCard());
                    if (ObjectUtil.equal(info.getPersonType(), 1)) {
                        deviceHistory.setMemberType(2);
                    }
                    if (StringUtils.isNotBlank(verifyWithSnapVo.getSanpPic())){
                        String record = fileInfoService.uploadFile(verifyWithSnapVo.getSanpPic(), FileTypeEnum.RECORD);
                        deviceHistory.setImage(record);
                    }
                    deviceHistoryService.save(deviceHistory);
                    response.setDesc("OK");
                    response.setCode("200");
                    return response;
                } else if (ObjectUtil.equal(info.getTempvalid(), 1)) {
                    log.info("设备收到【{}】访客通行记录", deviceBase.getName());
                    Visitor visitor = visitorService.getById(info.getCustomizeID().toString().substring(1));
                    if (visitor==null){
                        response.setDesc("OK");
                        response.setCode("200");
                        return response;
                    }
                    VisitorHistory visitorHistory = new VisitorHistory();
                    visitorHistory.setDeviceName(deviceBase.getName());
                    visitorHistory.setDeviceBaseId(deviceBase.getId());
                    visitorHistory.setVisitorId(visitor.getId());
                    visitorHistory.setDeviceCurrentDate(cpmparedDate);
                    visitorHistory.setIcNum(verifyWithSnapVo.getInfo().getRFIDCard());
                    visitorHistory.setVisitorName(visitor.getName());
                    // 8寸一体机
                    visitorHistory.setType(7);
                    if (ObjectUtil.isNotEmpty(visitor.getOrgId())) {
                        visitorHistory.setOrgId(visitor.getOrgId());
                        SysOrg sysOrg = sysOrgService.getById(visitor.getOrgId());
                        if (sysOrg != null) {
                            visitorHistory.setOrgName(sysOrg.getName());
                        }
                    }
                    if (StringUtils.isNotBlank(verifyWithSnapVo.getSanpPic())){
                        String record = fileInfoService.uploadFile(verifyWithSnapVo.getSanpPic(), FileTypeEnum.RECORD);
                        visitorHistory.setImage(record);
                    }
                    visitorHistory.setVerifyType("1");
                    visitorHistory.setIcNum(info.getRFIDCard());
                    visitorHistoryService.save(visitorHistory);
                    response.setDesc("OK");
                    response.setCode("200");
                    return response;
                }

            } else {
                log.error("设备不存在【{}】", JSON.toJSONString(verifyWithSnapVo));
                response.setCode("200");
                response.setDesc("OK");
                return response;
            }
        } catch (Exception e) {
            log.error("通行记录上传发生错误【{}】", ExceptionUtil.getMessage(e));
            response.setCode("200");
            response.setDesc("OK");
            return response;
        }
        response.setDesc("OK");
        response.setCode("200");
        return response;

    }


    @PostMapping("/subscribe/Card")
    public HeartBeat.Response cardReport(@RequestBody String body) {
        HeartBeat.Response response = new HeartBeat.Response();
        try {
            CardVo cardVo = JSON.parseObject(body, CardVo.class);
            log.info("收到刷卡通行记录【{}】", body);
            List<Visitor> list = visitorService.list(new LambdaQueryWrapper<Visitor>().eq(Visitor::getIcCard, cardVo.getInfo().getCardNo()).eq(Visitor::getStatus, VisitorConstant.EXAMINATION_PASSD));
            if (CollectionUtil.isNotEmpty(list) && list.size() > 1) {
                log.error("卡【{}】被多个访客绑定", cardVo.getInfo().getCardNo());
                response.setDesc("OK");
                response.setCode("200");
                return response;
            }
            DateTime cpmparedDate = DateUtil.parse(cardVo.getInfo().getCreateTime().replace("T", " "), "yyyy-MM-dd HH:mm:ss");
            DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceId, cardVo.getInfo().getDeviceID()));
            if (deviceSet != null) {
                DeviceBase deviceBase = deviceBaseService.getById(deviceSet.getDeviceBaseId());
                if (deviceBase == null) {
                    log.error("设备不存在【{}】", JSON.toJSONString(cardVo));
                    response.setCode("200");
                    response.setDesc("OK");
                    return response;
                }
                // 访客通行记录
                if (CollectionUtil.isNotEmpty(list)) {
                    log.info("设备收到【{}】访客通行记录", deviceBase.getName());
                    Visitor visitor = list.get(0);
                    VisitorHistory visitorHistory = new VisitorHistory();
                    visitorHistory.setDeviceName(deviceBase.getName());
                    visitorHistory.setDeviceBaseId(deviceBase.getId());
                    visitorHistory.setVisitorId(visitor.getId());
                    visitorHistory.setDeviceCurrentDate(cpmparedDate);
                    visitorHistory.setVisitorName(visitor.getName());
                    // 8寸一体机
                    visitorHistory.setType(7);
                    if (ObjectUtil.isNotEmpty(visitor.getOrgId())) {
                        visitorHistory.setOrgId(visitor.getOrgId());
                        SysOrg sysOrg = sysOrgService.getById(visitor.getOrgId());
                        if (sysOrg != null) {
                            visitorHistory.setOrgName(sysOrg.getName());
                        }
                    }
                    String record = fileInfoService.uploadFile(cardVo.getInfo().getSanpPic(), FileTypeEnum.RECORD);
                    visitorHistory.setImage(record);
                    visitorHistory.setVerifyType("1");
                    visitorHistory.setIcNum(cardVo.getInfo().getCardNo());
                    visitorHistoryService.save(visitorHistory);
                    response.setDesc("OK");
                    response.setCode("200");
                    return response;
                } else {
                    log.info("设备收到【{}】内部人员通行记录", deviceBase.getName());
                    MemberUser member = memberUserService.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getIcCard, cardVo.getInfo().getCardNo()));
                    DeviceHistory deviceHistory = new DeviceHistory();
                    deviceHistory.setDeviceBaseId(deviceBase.getId());
                    deviceHistory.setDeviceName(deviceBase.getName());
                    if (member != null) {
                        deviceHistory.setMemberJobNum(member.getJobNum());
                        deviceHistory.setOrgId(member.getOrgId());
                        deviceHistory.setMemberName(member.getName());
                        deviceHistory.setMemberId(member.getId());
                        if (ObjectUtil.equal(member.getPersonType(), 2)) {
                            deviceHistory.setMemberType(2);
                        }
                    }
                    deviceHistory.setDeviceCurrentDate(cpmparedDate);
                    deviceHistory.setIcNum(cardVo.getInfo().getCardNo());
                    if (StringUtils.isNotBlank(cardVo.getInfo().getSanpPic())) {
                        String record = fileInfoService.uploadFile(cardVo.getInfo().getSanpPic(), FileTypeEnum.RECORD);
                        deviceHistory.setImage(record);
                    }
                    deviceHistoryService.save(deviceHistory);
                    response.setDesc("OK");
                    response.setCode("200");
                    return response;
                }
            } else {
                log.error("设备尚未配置【{}】", JSON.toJSONString(cardVo));
                response.setCode("200");
                response.setDesc("OK");
                return response;
            }
        } catch (Exception e) {
            log.error("刷卡通行记录发生错误【{}】", body);
            response.setCode("200");
            response.setDesc("OK");
            return response;
        }

    }

}
